Before and after puzzle [Hash]

Time: O(LxRLogR); Space: O(Lx(N+R)); medium

Given a list of phrases, generate a list of Before and After puzzles.

A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.

Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase.

Return the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j. Note that the order of matching two phrases matters, we want to consider both orders.

You should return a list of distinct strings sorted lexicographically.

Example 1:

Input: phrases = [“writing code”,“code rocks”]

Output: [“writing code rocks”]

Example 2:

Input: phrases =

[
 "mission statement",
 "a quick bite to eat",
 "a chip off the old block",
 "chocolate bar",
 "mission impossible",
 "a man on a mission",
 "block party",
 "eat my words",
 "bar of soap"
 ]

Output:

[
 "a chip off the old block party",
 "a man on a mission impossible",
 "a man on a mission statement",
 "a quick bite to eat my words",
 "chocolate bar of soap"
]

Example 3:

Input: phrases = [“a”,“b”,“a”]

Output: [“a”]

Constraints:

  • 1 <= len(phrases) <= 100

  • 1 <= len(phrases[i]) <= 100

[1]:
import collections

class Solution1(object):
    """
    Time: O(L*RLogR), L is the max length of phrases, R is the number of result, could be up to O(N^2)
    Space: O(L*(N+R)), N is the number of phrases
    """
    def beforeAndAfterPuzzles(self, phrases):
        """
        :type phrases: List[str]
        :rtype: List[str]
        """
        lookup = collections.defaultdict(list)
        for i, phrase in enumerate(phrases):
            right = phrase.rfind(' ')
            word = phrase if right == -1 else phrase[right+1:]
            lookup[word].append(i)

        result_set = set()
        for i, phrase in enumerate(phrases):
            left = phrase.find(' ')
            word = phrase if left == -1 else phrase[:left]
            if word not in lookup:
                continue
            for j in lookup[word]:
                if j == i:
                    continue
                result_set.add(phrases[j] + phrase[len(word):])

        return sorted(result_set)
[2]:
s = Solution1()

phrases = ["writing code","code rocks"]
assert s.beforeAndAfterPuzzles(phrases) == ["writing code rocks"]

phrases = [
     "mission statement",
     "a quick bite to eat",
     "a chip off the old block",
     "chocolate bar",
     "mission impossible",
     "a man on a mission",
     "block party",
     "eat my words",
     "bar of soap"
     ]
assert s.beforeAndAfterPuzzles(phrases) == [
     "a chip off the old block party",
     "a man on a mission impossible",
     "a man on a mission statement",
     "a quick bite to eat my words",
     "chocolate bar of soap"
    ]

phrases = ["a","b","a"]
assert s.beforeAndAfterPuzzles(phrases) == ["a"]